// pages/user_end/payorder/payorder.js
const app = getApp();
const request = require('../../../utils/request.js');
const url = require('../../../utils/url.js');
const cookie = require('../../../utils/cookie.js');
const WxParse = require('../../../wxParse/wxParse.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {	  
	countdown: 5,
	addr:'',
    id: 0,
	area:'',
	region:'',
    address_id: 0,
    coupon_id: 0,
    servicenums: 1,
    isReserve: 0, //是否选择预约日期
    worker_avatar: '',
    worker_name: '',
    order: [],
    worklist: [],
	retentionlist:[],
    worker_id: 0,
    show: false,
    show1: false,
    nindex: 0,
    datelist: [],
    timelist: [],
    timelist2: [],
    reserveDate: "", //预约日期
    reserveShow: "", //服务开始时间
    reserveTime: 0,
    service_category_id: 0,
    service_desc: "",
    service_desc_images: [],
    remark: "",
    active: 1,
    imgs: [],
    picList: [],
    service_time_unit: 30, //服务时间区间
    service_multiple: false, //单选
    cnum: 0, //选中数
    token: '',
    checkContract: 0, //选择合同
    agreement:true,
	buttonDisabled:true,
	categoryname:'',
	tax_title:'',
	tax_no:'',
	good:'',
	index:0,
	btnshow:true,
	lat:'',
	lng:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id: options.id,
	  categoryname:options.categoryname
    })
    var that = this;
    cookie.getCookie('userInfo', function (res) {
      if (res) {
        var etime = Date.parse(new Date()) / 1000;
        
        if (etime < res.expiretime) {
          that.setData({
            login: 1,
            token: res.token
          })
		  that.getcontent();
        }
      }
    })

   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  changeAgreement(){
      this.setData({
          agreement:false
      })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;
    if (that.data.token) {
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  getcontent(){
	  var that = this;
	  wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
	  
	  request.request('https://mcc.huotukj.com/index.php/api/xiservice.service_category/ordercontract', {}, url.REQUEST_METHOD_GET).then((res) => {
	    wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
	    if(res.data.code==1){
	      that.setData({
	        info:res.data.data
	      })
	      if(!res.data.data){
	       wx.showToast({
	         title:'该文章不存在!',
	         icon:'none'
	       });			
	       setTimeout(function(){
	         wx.navigateBack({
	           delta:1
	         })
	       },1500)							 
	      }
	      // wx.setNavigationBarTitle({
	      //   title: res.data.data.name,
	      // });
	      let content = res.data.data.content;
		  console.log(content);
	      WxParse.wxParse('htcontent', 'html', content, that, 0)
		  // that.data.countdownInterval = setInterval(that.countdownTimer, 3000);
		 that.countdownTimer();
	    }
	  })  
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  
    countdownTimer: function() {
      const that = this;
      let countdown = that.data.countdown;  
	  // 设置定时器
	  let timer = setInterval(function() {
	    countdown--;	    
		that.setData({
		  countdown: countdown
		});
		console.log(that.data.countdown);
	    // 当倒计时结束时
	    if (countdown <= 0) {
	      clearInterval(timer);
	     that.setData({
	       countdown: 0,
	       buttonDisabled: false
	     });
	    }
	  }, 1000);  
	  
     
    },
  choseTime: function () {
    this.setData({
      show1: true
    })
  },
  choselocation(){
     var that = this;
     wx.chooseLocation({
       success: function(res) {
         console.log("地图点击事件：" + JSON.stringify(res));
         that.setData({
           addr:res.address,
           lat : res.latitude,
           lng: res.longitude,
           setlocation:1 
         });
  
       }
     })
  },
  goAddress() {
    wx.navigateTo({
      url: '../address_chose/address_chose?type=1'
    })
  },
  open() {
    this.setData({
      show: true
    });
  },
  close() {
    this.setData({
      show: false,
      show1: false
    })
  },
  
  payOrderMsg:function(){
	  var that = this;
	  wx.requestSubscribeMessage({
      tmplIds: [
	  		'0fHW_V0mpcRkwvflDCdY9393_a-p-0xW08pRO8pNSMk', //诊断完成通知
	  		'Z-OFKRd2aAOX20azHmd6D30cXIdIGaW1jX-QWEHieHc' //拒绝通知(入驻拒绝)通知服务人员
	    ],
	    success: (res) => {
	  	  console.log(res)
		 wx.showModal({
		   title: '提示',
		   content: '本诊断需求仅请专家对来样图片进行诊断，明确知道平台专家不对诊断结果负法律责任',
		   success (res) {
		     if (res.confirm) {
		       that.payOrder(that);
		     } else if (res.cancel) {
		       console.log('用户点击了取消')
		     }
		   }
		 })	     
	    },
	    fail: (res) => {
	  	    console.log(res)
	      that.payOrder(that);
	    },
	  })
  },
  payOrder: function (that) {
	  
	  console.log('lat:'+that.data.lat);
    // var that = this;
	if(that.data.lat=='')
	{
		wx.showToast({
		  title: '请选择地址',
		  icon: "none"
		})
		return false;
	}
    if (that.data.id == 0) {
      wx.showToast({
        title: '参数错误',
        icon: "none"
      })
      return false;
    }
    //判断地址信息
    if (that.data.remark == '') {
      wx.showToast({
        title: '请输入问题描述',
        icon: "none"
      })
      return false;
    }
    that.setData({
      service_desc_images: that.data.picList
    })

    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      servicenums: 1,
      coupon_id: 0,
      remark: that.data.remark,
      service_desc_images: that.data.service_desc_images,
	  retention_amount:that.data.retention_amount,
	  arrive_address:that.data.addr,
	  addr:that.data.addr,
	   lat:that.data.lat,
	   lng:that.data.lng
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
	
    request.request(url.createexpertorder, param, url.REQUEST_METHOD_POST).then((res) => {
    wx.showNavigationBarLoading(); 
      if (res.data.code == 1) {
        //直接支付成功
        //跳转订单详情页
        let orderId = res.data.data.id;
        if (res.data.data.pay_money > 0) {
          var config = JSON.parse(res.data.data.wxconfig);
          console.log("成功", JSON.parse(res.data.data.wxconfig));
		  
          wx.requestPayment({
            'timeStamp': config.timestamp,
            'nonceStr': config.nonceStr,
            'package': config.package,
            'signType': config.signType,
            'paySign': config.paySign,
            'success': function (res2) {
              console.log("成功", res2)
			    wx.showToast({
			      title: res2.errMsg,
			      icon: 'none'
			    })
              if (res2.errMsg == 'requestPayment:ok') {
				  wx.showToast({
				    title: '支付成功,请等待专家诊断',
				    icon: 'none'
				  })
               
                 setTimeout(function () {
                   wx.navigateTo({
                     url: '/pages/user_end/index/index'
                   })
               }, 1500)
                return false;
              }
            },
            'fail': function (res2) {
              console.log("失败", res2)
              // wx.navigateTo({
              //   url: '/pages/user_end/order_expert_detail/order_expert_detail?id=' + orderId,
              // })
              return false;
            },
            'complete': function (res2) {}
          })
        } else {
          wx.showToast({
            title: '支付成功',
            icon: 'none'
          })
          wx.navigateTo({
            // url: '../order_choose/order_choose?id=' + orderId,
			url: 'pages/user_end/index/index',
          })
          return false;
        }
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  changedesc(e) {
    var desc = e.detail.value;
    this.setData({
      service_desc: desc
    })
  },
  changeremark(e) {
    var remark = e.detail.value;
    this.setData({
      remark: remark
    })
  },
  deleteImg: function (e) {
    var imgs = this.data.imgs;
    var picList = this.data.picList;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    picList.splice(index, 1);
    this.setData({
      imgs: imgs,
      picList: picList
    });
    console.log(picList);
  },
  chooseImg: function (e) {
    var that = this;
    var imgs = this.data.imgs;
    if (imgs.length >= 3) {
      this.setData({
        lenMore: 1
      });
      setTimeout(function () {
        that.setData({
          lenMore: 0
        });
      }, 2500);
      return false;
    }
    var count = 3 - imgs.length;
    if (count < 1) {
      return false;
    }

    wx.chooseImage({
      count: count, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        if (res.errMsg == "chooseImage:ok") {
          wx.showLoading({ //显示loding提示框
            title: '正在上传中...',
          })
          let picList = that.data.picList
          var imgs = that.data.imgs;
          res.tempFilePaths.forEach((item, index) => {
            imgs.push(item)
            that.setData({
              imgs: imgs,
            });
            wx.uploadFile({
              url: url.HttpServerHostAddress + url.uploadpic,
              filePath: item,
              name: 'file',
              formData: {
                token: that.data.token
              },
              success: function (res) {
                let ress = JSON.parse(res.data)
                if (ress.code == 1) {
                  var picList = that.data.picList;
                  picList.push(JSON.parse(res.data).data.url);
                  that.setData({
                    picList: picList,
                  })
                  console.log(picList);
                } else {
                  wx.showToast({
                    title: JSON.parse(res.data).msg,
                    icon: 'none',
                    duration: 3000
                  })
                  return;
                }
              },
              fail: res => {
                console.log(res)
              }
            })
          })
          wx.hideLoading(); //隐藏loading提示框
        }
      }
    });
  },
  choseContract(e) {
    var check = e.currentTarget.dataset.checked;
    this.setData({
      checkContract: check
    })
  },
  choseArea(e) {
    var area = e.currentTarget.dataset.area;
	console.log(area);
    this.setData({
      area: area
    })
  },
  choseRegion(e) {
    var area = e.currentTarget.dataset.area;
  	console.log(area);
    this.setData({
      region: area
    })
  },
})